﻿using BO.Infrastructure.StaticData;
using BO.Infrastructure.Utils;
using BO.ProjectManager;
using BugManager;
using CBL;
using DAL;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml.Linq;
using Utilities.Entities;

namespace BO.News
{
    public class NewsBO_NoCache : INewsBO
    {
        private readonly NewsBO _cachedLayer = new NewsBO();

        private static NewsBO_NoCache _ownerInstance;
        public static INewsBO GetInstance()
        {
            return _ownerInstance ?? (_ownerInstance = new NewsBO_NoCache());
        }

        #region INewsBO Members
        public DataTable GetNewsByPosition(int top, int typeId, int topExclusion = 0, int zoneId = 0, bool getDataFromMasterDataBase = false)
        {
            DataTable dt = null;

            if (getDataFromMasterDataBase)
            {
                try
                {
                    using (var db = new MasterDB())
                    {
                        dt = db.StoredProcedures.GetNewsByPosition(top, typeId, topExclusion, zoneId);
                    }
                }
                catch (Exception ex)
                {
                    ErrorManager.Log(ex);
                }
            }
            if (dt == null || dt.Rows.Count <= 0)
            {
                try
                {
                    using (var db = new MainDB())
                    {
                        dt = db.StoredProcedures.GetNewsByPosition(top, typeId, topExclusion, zoneId);
                    }
                }
                catch (Exception ex)
                {
                    ErrorManager.Log(ex);
                }
            }
            return DataFomatter.ReformatNewsTable(dt);
        }

        public DataTable GetListNews(int pageIndex, int pageSize, int topExclusion = 0, int zoneId = 0)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetListNews(pageIndex, pageSize, topExclusion, zoneId);
            }
            return DataFomatter.ReformatNewsTable(dt);
        }

        public DataTable GetListNewsWithSubCategory(int pageIndex, int pageSize, int topExclusion = 0, int zoneId = 0)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetListNewsWithSubCategory(pageIndex, pageSize, topExclusion, zoneId);
            }
            return DataFomatter.ReformatNewsTable(dt);
        }

        public int GetTotalPagesOfListNews(int pageSize, int topExclusion = 0, int zoneId = 0)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.CountNews(topExclusion, zoneId);
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                int n;
                int.TryParse(dt.Rows[0][0].ToString(), out n);
                return (int)Math.Ceiling((decimal)n / pageSize);
            }
            return default(int);
        }

        public DataTable GetNewsDetail(long newsId)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetNewsDetail(newsId);
            }
            if (dt == null || dt.Rows.Count <= 0)
            {
                using (var db = new MasterDB())
                {
                    dt = db.StoredProcedures.GetNewsDetail(newsId);
                }
            }
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    dt.Rows[0][SqlConstants.NewsPublish.Content] =
            //        dt.Rows[0][SqlConstants.NewsPublish.Content].ToString().TrimEnd("<p> </p>".ToCharArray());
            //}
            return dt;
        }

        public DataTable GetEmbedNewsOnPage(int top, int zoneId, int type)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetEmbedNewsOnPage(top, zoneId, type);
            }
            return DataFomatter.ReformatNewsTable(dt);
        }

        public DataTable GetHotNews(int top, int zoneId)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetHotNews(top, zoneId);
            }
            return DataFomatter.ReformatNewsTable(dt);
        }

        public DataTable GetCareableNews(int top)
        {
            try
            {
                DataTable dt;
                using (var db = new MSohaDB())
                {
                    dt = db.StoredProcedures.GetCareableNews(top);
                }
                return DataFomatter.ReformatNewsTable(dt);

            }
            catch (Exception ex)
            {
                ErrorManager.Log("NewsBO_NoCache", "GetCareableNews", ex.ToString());
            }
            return null;
        }

        public DataTable GetOlderNews(int top, int zoneId, long newsId, DateTime publishedDate)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetOlderNews(top, zoneId, newsId, publishedDate);
            }
            return DataFomatter.ReformatNewsTable(dt);
        }

        public CategoryObject GetCategoryDetail(string catUrl)
        {
            var allCategories = _cachedLayer.GetAllCategories();
            return allCategories == null
                       ? null
                       : allCategories.FirstOrDefault(c => catUrl.Equals(c.DisplayUrl, StringComparison.InvariantCultureIgnoreCase));

        }

        public CategoryObject GetCategoryDetail(int catId)
        {
            var allCategories = _cachedLayer.GetAllCategories();
            return allCategories == null
                       ? null
                       : allCategories.FirstOrDefault(c => catId == c.Id);

        }

        public TagObject GetTagDetail(int tagId)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetTagDetail(tagId);
            }
            if (dt != null && dt.Rows.Count == 1)
            {
                var r = dt.Rows[0];
                var displayUrl = r[SqlConstants.Tag.Name].ToString().ToKoDauAndGach();
                var isThread = bool.Parse(r[SqlConstants.Tag.IsThread].ToString());
                return new TagObject
                           {
                               Id = tagId,
                               Name = r[SqlConstants.Tag.Name].ToString(),
                               DisplayUrl = displayUrl,
                               Url = isThread ? PresentationUtils.UrlBuilder.BuildThreadUrl(tagId, displayUrl, false) : PresentationUtils.UrlBuilder.BuildTagUrl(displayUrl, false),
                               Description = r[SqlConstants.Tag.Description].ToString(),
                               IsHot = bool.Parse(r[SqlConstants.Tag.IsHotTag].ToString()),
                               IsThread = isThread
                           };
            }
            return null;
        }

        public CategoryObject GetCategoryMetaData(int catId)
        {
            var allCategories = _cachedLayer.GetAllCategoriesMetaData();
            var result = allCategories == null
                       ? null
                       : allCategories.FirstOrDefault(c => catId == c.Id);
            if (result != null && result.ParentId == 0 && !result.ThemeUrl.StartsWith("http"))
            {
                var currentStorageSetting = PMBO.GetCurrentStorageConfig();
                if (currentStorageSetting.IsUsed)
                {
                    result.ThemeUrl = string.Format("{0}{1}", currentStorageSetting.Domain.TrimEnd('/'), result.ThemeUrl);
                }
            }
            return result;
        }

        public List<CategoryObject> GetAllCategories()
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetAllCategories();
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                var query = from DataRow r in dt.Rows
                            let parentId = PresentationUtils.Object2Integer(r[SqlConstants.Zone.ParentId].ToString())
                            select new CategoryObject
                                       {
                                           Id = PresentationUtils.Object2Integer(r[SqlConstants.Zone.Id].ToString()),
                                           Name = r[SqlConstants.Zone.Name].ToString(),
                                           DisplayUrl = r[SqlConstants.Zone.ShortUrl].ToString().ToLower(),
                                           Url = 
                                            PresentationUtils.UrlBuilder.BuildCatUrl(r[SqlConstants.Zone.ShortUrl].ToString(), false),
                                           ParentId = parentId,
                                           SortOrder = PresentationUtils.Object2Integer(r[SqlConstants.Zone.SortOrder].ToString())
                                       };
                return query.ToList();
            }
            return null;
        }

        public OriginalSiteObject GetOriginalSiteDetail(int siteId)
        {
            var sites = _cachedLayer.GetAllOriginalSites();
            return sites == null ? null : sites.FirstOrDefault(o => o.Id == siteId);
        }

        public DataTable GetNewsByTag(int tagId, int pageIndex, int pageSize)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetNewsByTag(tagId, pageIndex, pageSize);
            }
            return DataFomatter.ReformatNewsTable(dt);
        }

        public int GetTotalPagesOfListNewsByTag(int tagId, int pageSize)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.CountNewsByTag(tagId);
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                int n;
                int.TryParse(dt.Rows[0][0].ToString(), out n);
                return (int)Math.Ceiling((decimal)n / pageSize);
            }
            return default(int);
        }

        public DataTable GetNewsByDate(int day, int month, int year, int pageIndex, int pageSize, int zoneId)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetNewsByDate(day, month, year, pageIndex, pageSize, zoneId);
            }
            return DataFomatter.ReformatNewsTable(dt);
        }

        public int GetTotalPagesOfListNewsByDate(int day, int month, int year, int pageSize, int zoneId)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.CountNewsByDate(day, month, year, zoneId);
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                int n;
                int.TryParse(dt.Rows[0][0].ToString(), out n);
                return (int)Math.Ceiling((decimal)n / pageSize);
            }
            return default(int);
        }

        public DataTable GetSportNewsByPosition(int top, int typeId, int topExclusion = 0, int zoneId = 0, bool getDataFromMasterDataBase = false)
        {
            DataTable dt;

            if (getDataFromMasterDataBase)
                using (var db = new MasterDB())
                    dt = db.StoredProcedures.GetSportNewsByPosition(top, typeId, topExclusion, zoneId);
            else
                using (var db = new MainDB())
                    dt = db.StoredProcedures.GetSportNewsByPosition(top, typeId, topExclusion, zoneId);

            return DataFomatter.ReformatNewsTable(dt);
        }

        public DataTable GetMostViewNews(int top, int zoneId)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetMostViewNews(top, zoneId);
            }
            return DataFomatter.ReformatNewsTable(dt);
        }

        public List<LiveNewsObject> GetLiveNews(long newsId)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetLiveNews(newsId);
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                var query = from DataRow r in dt.Rows
                            select new LiveNewsObject
                                       {
                                           Id = PresentationUtils.Object2Integer(r[SqlConstants.NewsLive.Id].ToString()),
                                           Content = r[SqlConstants.NewsLive.Content].ToString(),
                                           PublishedDate = PresentationUtils.Object2DateTime(r[SqlConstants.NewsLive.PublishedDate].ToString()).ToString("hh:mm")
                                       };
                return query.ToList();
            }
            return null;
        }

        public DataTable GetEmbedNews(int top, int type, int zoneId = 0)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetEmbedNews(top, type, zoneId);
            }
            return DataFomatter.ReformatNewsTable(dt);
        }

        public NewsObject SEO_GetNewsDetail(long newsId)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.SEO_GetNewsDetail(newsId);
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                var r = dt.Rows[0];
                return new NewsObject
                {
                    NewsId = newsId,
                    Title = r[SqlConstants.SEOMetaNews.MetaTitle].ToString(),
                    Description = r[SqlConstants.SEOMetaNews.MetaDescription].ToString(),
                    Keywords = r[SqlConstants.SEOMetaNews.MetaKeyword].ToString(),
                    NewsKeywords = r[SqlConstants.SEOMetaNews.MetaNewsKeyword].ToString()
                };
            }
            return null;
        }

        public DataTable GetNewsByType(int top, int type, int zoneId)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetNewsByType(top, type, zoneId);
            }
            return dt != null ? DataFomatter.ReformatNewsTable(dt) : null;
        }

        public List<EmbedGroup> GetEmbedGroup()
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetEmbedGroup();
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                var lstGroup = new List<int>();
                var result = new List<EmbedGroup>();
                foreach (DataRow r in dt.Rows)
                {
                    var groupId = (int)r[SqlConstants.EmbedGroup.Id];
                    if (lstGroup.Contains(groupId)) continue;
                    result.Add(new EmbedGroup
                                   {
                                       TepmlateId = PresentationUtils.Object2Integer(r[SqlConstants.EmbedGroup.TemplateId].ToString()),
                                       Visible = PresentationUtils.Object2Boolean(r[SqlConstants.EmbedGroup.IsVisible].ToString()),
                                       SortOrder = PresentationUtils.Object2Integer(r["GroupSortOrder"].ToString()),
                                       Zones = (from DataRow row2 in dt.Rows
                                                where groupId == PresentationUtils.Object2Integer(row2[SqlConstants.EmbedGroup.Id].ToString())
                                                select new ZoneInEmbedGroup
                                                           {
                                                               ZoneId = PresentationUtils.Object2Integer(row2[SqlConstants.ZoneInEmbedGroup.ZoneId].ToString()),
                                                               GroupId = groupId,
                                                               SortOrder = PresentationUtils.Object2Integer(row2[SqlConstants.ZoneInEmbedGroup.SortOrder].ToString())
                                                           }).ToArray()
                                   });
                    lstGroup.Add(groupId);
                }
                return result;
            }
            return null;

        }

        public EmbedThreadGroup GetEmbedThreads(int top, int zoneId, int type)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetEmbedThreads(top, zoneId, type);
            }
            if (dt != null && dt.Rows.Count > 0)
            {

                var threads = new ThreadInEmbedGroup[dt.Rows.Count];
                for (var i = 0; i < dt.Rows.Count; i++)
                {
                    var r = dt.Rows[i];
                    var threadId = PresentationUtils.Object2Integer(r[SqlConstants.Tag.Id].ToString());
                    var info = new TagObject
                        {
                            Id = threadId,
                            Name = r[SqlConstants.Tag.Name].ToString(),
                            IsThread = PresentationUtils.Object2Boolean(r[SqlConstants.Tag.IsThread].ToString()),
                            Url = PresentationUtils.UrlBuilder.BuildThreadUrl(
                                threadId,
                                r[SqlConstants.Tag.Name].ToString())
                        };
                    threads[i] = new ThreadInEmbedGroup
                        {
                            TemplateId = PresentationUtils.Object2Integer(r[SqlConstants.Tag.TemplateId].ToString()),
                            OwnerInfo = info
                        };
                }
                return new EmbedThreadGroup
                {
                    ZoneId = zoneId,
                    Threads = threads
                };
            }
            return null;
        }

        public TagObject GetTagDetail(string tagUrl)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetTagDetail(tagUrl);
            }
            if (dt != null && dt.Rows.Count == 1)
            {
                var r = dt.Rows[0];
                var displayUrl = r[SqlConstants.Tag.Name].ToString().ToKoDauAndGach();
                var isThread = bool.Parse(r[SqlConstants.Tag.IsThread].ToString());
                var tagId = PresentationUtils.Object2Integer(r[SqlConstants.Tag.Id].ToString());
                var avatar = r[SqlConstants.Tag.Avatar].ToString();
                var body = r[SqlConstants.Tag.Content].ToString();

                var description = string.IsNullOrEmpty(r[SqlConstants.Tag.TagInit].ToString())
                    ? r[SqlConstants.Tag.Description].ToString()
                    : r[SqlConstants.Tag.TagInit].ToString();

                return new TagObject
                {
                    Id = PresentationUtils.Object2Integer(r[SqlConstants.Tag.Id].ToString()),
                    Name = r[SqlConstants.Tag.Name].ToString(),
                    DisplayUrl = displayUrl,
                    Url = isThread ? PresentationUtils.UrlBuilder.BuildThreadUrl(tagId, displayUrl, false) : PresentationUtils.UrlBuilder.BuildTagUrl(displayUrl, false),
                    Description = description,
                    IsHot = bool.Parse(r[SqlConstants.Tag.IsHotTag].ToString()),
                    IsThread = isThread,
                    Content = body,
                    Avatar = avatar,
                    Keywords = r[SqlConstants.Tag.TagMetaKeyword].ToString(),
                    Title = r[SqlConstants.Tag.TagTitle].ToString()
                };
            }
            return null;
        }

        public DataTable GetBaiGiaoLuuTrucTuyen(int newsId)
        {
            using (var db = new IOnlineDB())
            {
                return db.StoredProcedures.GetBaiGiaoLuuTrucTuyen(newsId);
            }
        }

        #endregion

        internal static List<Season> GetLichThiDau()
        {
            DataTable dt;
            using (var db = new CrawlerSystemDB())
            {
                dt = db.StoredProcedures.GetLichThiDau();
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                var query = from DataRow r0 in dt.Rows
                            group r0 by r0["SeasonName"].ToString() into temp
                            select new Season
                            {
                                Name = temp.Key,
                                Bet = (from DataRow r in dt.Rows
                                       where temp.Key.Equals((r["SeasonName"].ToString()))
                                       select new Betting
                                       {
                                           SeasionId = PresentationUtils.Object2Integer(r["SeasonId"].ToString()),

                                           HomeTeamId = PresentationUtils.Object2Integer(r["HomeTeamId"].ToString()),
                                           VisitTeamId = PresentationUtils.Object2Integer(r["VisitTeamId"].ToString()),
                                           TopTeamId = PresentationUtils.Object2Integer(r["TopTeamId"].ToString()),

                                           HomeTeamName = r["HomeTeamName"].ToString(),
                                           VisitTeamName = r["VisitTeamName"].ToString(),
                                           AsiaContract = r["AsiaContract"].ToString(),
                                           AsiaVisitPrice = r["AsiaVisitPrice"].ToString(),
                                           AsiaHomePrice = r["AsiaHomePrice"].ToString(),
                                           EuropeContract = r["EuropeContract"].ToString(),
                                           EuropeHomePrice = r["EuropeHomePrice"].ToString(),
                                           EuropeVisitPrice = r["EuropeVisitPrice"].ToString(),
                                           MatchTime = r["MatchTime"].ToString(),
                                           OverPrice = r["OverPrice"].ToString(),
                                           OverUnderContract = r["OverUnderContract"].ToString(),
                                           UnderPrice = r["UnderPrice"].ToString(),
                                       }).ToArray()
                            };

                return query.ToList();


            }
            return null;
        }

        internal static List<SportRanking> GetBangXepHang()
        {
            DataTable dt;
            using (var db = new CrawlerSystemDB())
            {
                dt = db.StoredProcedures.GetBangXepHang();
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                var query = from DataRow r0 in dt.Rows
                            group r0 by r0["CountryName"].ToString() into temp
                            select new SportRanking
                                       {
                                           CountryName = temp.Key,
                                           Items = (from DataRow r in dt.Rows
                                                    where temp.Key.Equals((r["CountryName"].ToString()))
                                                    orderby PresentationUtils.Object2Integer(r["Rank"].ToString())
                                                    select new SportRankingItem
                                                               {
                                                                   CountryName = temp.Key,
                                                                   MatchCount = r["MatchCount"].ToString(),
                                                                   Offset = r["Offset"].ToString(),
                                                                   Points = r["Points"].ToString(),
                                                                   Rank = PresentationUtils.Object2Integer(r["Rank"].ToString()),
                                                                   TeamId = PresentationUtils.Object2Integer(r["TeamId"].ToString()),
                                                                   TeamName = r["TeamName"].ToString()
                                                               }).ToArray()
                                       };

                return query.ToList();


            }
            return null;
        }

        public List<CategoryObject> GetAllCategoriesMetaData(out string fileDependency)
        {
            var filePath = HttpContext.Current.Server.MapPath(DefinedConstants.FilePath.CategoriesMetaData);
            if (File.Exists(filePath))
            {
                var doc = XElement.Load(filePath);
                var query = doc.Descendants("zone").Select(c => new CategoryObject
                {
                    Id = (int)c.Attribute("id"),
                    Name = c.Attribute("name") == null ? string.Empty : (string)c.Attribute("name"),
                    Description = c.Attribute("description") == null ? string.Empty : (string)c.Attribute("description"),
                    Keywords = c.Attribute("keywords") == null ? string.Empty : (string)c.Attribute("keywords"),
                    Title = c.Attribute("title") == null ? string.Empty : (string)c.Attribute("title"),
                    Theme = c.Attribute("theme") == null ? string.Empty : (string)c.Attribute("theme"),
                    ThemeUrl =
                    c.Attribute("themeUrl") != null
                    ? (string)c.Attribute("themeUrl")
                    : c.Attribute("theme") == null
                        ? string.Empty
                        : string.Format("/Styles/Themes/{0}.css", (string)c.Attribute("theme"))
                });
                fileDependency = filePath;
                return query.ToList();
            }
            fileDependency = string.Empty;
            return null;
        }

        public List<OriginalSiteObject> GetAllOriginalSites(out string fileDependency)
        {
            var filePath = HttpContext.Current.Server.MapPath(DefinedConstants.FilePath.OriginalSites);
            if (File.Exists(filePath))
            {
                var doc = XElement.Load(filePath);
                var sites = doc.Descendants("site");
                var xElements = sites as XElement[] ?? sites.ToArray();
                if (xElements.Any())
                {
                    var query = from o in xElements
                                select new OriginalSiteObject
                                {
                                    Id = o.Attribute("id") == null ? 0 : (int)o.Attribute("id"),
                                    Name = o.Attribute("name") == null ? string.Empty : (string)o.Attribute("name"),
                                    Url = o.Attribute("url") == null ? string.Empty : (string)o.Attribute("url")
                                };
                    fileDependency = filePath;
                    return query.ToList();
                }
            }
            fileDependency = string.Empty;
            return null;
        }

        public List<LinkObject> GetSportSubMenu(out string fileDependency)
        {
            var filePath = HttpContext.Current.Server.MapPath(DefinedConstants.FilePath.SportSubMenu);
            if (File.Exists(filePath))
            {
                var doc = XElement.Load(filePath);
                var sites = doc.Descendants("link");
                var xElements = sites as XElement[] ?? sites.ToArray();
                if (xElements.Any())
                {
                    var query = from o in xElements
                                select new LinkObject
                                {
                                    Url = o.Attribute("url") == null ? string.Empty : (string)o.Attribute("url"),
                                    Text = o.Attribute("text") == null ? string.Empty : (string)o.Attribute("text"),
                                    Title = o.Attribute("title") == null ? string.Empty : (string)o.Attribute("title")
                                };
                    fileDependency = filePath;
                    return query.ToList();
                }
            }
            fileDependency = string.Empty;
            return null;
        }

        internal static VoteObject GetVote(int voteId)
        {
            try
            {
                DataTable dt;
                using (var db = new VoteDB())
                {
                    dt = db.StoredProcedures.GetVoteAnswers(voteId);
                }

                var result = new VoteObject { ID = voteId };

                if (dt != null && dt.Rows.Count > 0)
                {
                    var answers = new VoteAnswerObject[dt.Rows.Count];
                    var allVoteNum = dt.Rows.Cast<DataRow>().Sum(row => PresentationUtils.Object2Integer(row[SqlConstants.VoteAnswer.VoteRate].ToString()));
                    for (var i = 0; i < dt.Rows.Count; i++)
                    {
                        var r = dt.Rows[i];
                        var answerObject = new VoteAnswerObject
                                               {
                                                   ID = PresentationUtils.Object2Integer(r[SqlConstants.Vote.ID].ToString()),
                                                   VoteRate = PresentationUtils.Object2Integer(r[SqlConstants.VoteAnswer.VoteRate].ToString())
                                               };
                        answerObject.VotePercent = allVoteNum == 0 ? 0 : answerObject.VoteRate / allVoteNum * 100;
                        answers[i] = answerObject;
                    }
                    result.VoteAnswers = answers;
                }

                return result;
            }
            catch (Exception ex)
            {
                ErrorManager.Log("NewsBO_NoCache", "GetVote", ex.ToString());
            }
            return null;
        }

        internal static void Vote(int voteId, int[] voteItemIDs)
        {
            try
            {
                using (var db = new VoteDB())
                {
                    foreach (var id in voteItemIDs)
                    {
                        db.StoredProcedures.Vote(voteId, id);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("NewsBO_NoCache", "Vote", ex.ToString());
            }
        }

        internal NewsObject GetNewsMetaData(long newsId)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetNewsMetaData(newsId);
            }
            if (dt == null || dt.Rows.Count <= 0)
            {
                using (var db = new MasterDB())
                {
                    dt = db.StoredProcedures.GetNewsMetaData(newsId);
                }
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                var r = dt.Rows[0];
                return new NewsObject
                {
                    NewsId = newsId,
                    Title = r[SqlConstants.NewsPublish.Title].ToString(),
                    Avatar = r[SqlConstants.NewsPublish.Avatar].ToString(),
                    DetailedAvatar = PresentationUtils.Photo.GetSourceImage(r[SqlConstants.NewsPublish.Avatar].ToString()),
                    DistributionDate = PresentationUtils.Object2DateTime(r[SqlConstants.NewsPublish.DistributionDate].ToString()),
                    Sapo = r[SqlConstants.NewsPublish.Sapo].ToString(),
                    Description = r[SqlConstants.NewsPublish.Sapo].ToString(),
                    Url = r[SqlConstants.NewsPublish.Url].ToString(),
                    OriginalUrl = PresentationUtils.UrlBuilder.BuildAbsoluteUrl(
                                 dt.Columns.Contains(SqlConstants.NewsPublish.OriginalUrl) && !string.IsNullOrEmpty(r[SqlConstants.NewsPublish.OriginalUrl].ToString())
                                    ? r[SqlConstants.NewsPublish.OriginalUrl].ToString()
                                    : r[SqlConstants.NewsPublish.Url].ToString()),
                    ShortUrl = PresentationUtils.UrlBuilder.BuildAbsoluteUrl(Regex.Replace(r[SqlConstants.NewsPublish.Url].ToString(), @"([^/]+)(-)(\d+)", "n$2$3")),
                    DetailedUrl = PresentationUtils.UrlBuilder.BuildAbsoluteUrl(r[SqlConstants.NewsPublish.Url].ToString()),
                    Keywords = r[SqlConstants.NewsPublish.TagItem].ToString().Replace(';', ','),
                    NewsKeywords = r[SqlConstants.NewsPublish.TagItem].ToString().Replace(';', ','),
                    Base64Title = CommonBusinessObject.EncodeBase64(HttpUtility.UrlEncode(r[SqlConstants.NewsPublish.Title].ToString())),
                    ZoneId = PresentationUtils.Object2Integer(r[SqlConstants.NewsPublish.ZoneId].ToString()),
                    Type = PresentationUtils.Object2Integer(r[SqlConstants.NewsPublish.Type].ToString())
                };
            }
            return null;
        }

        public static DataTable GetNewsByTime(DateTime startDate, DateTime endDate)
        {
            using (var db = new MainDB())
            {
                return db.StoredProcedures.GetNewsByTime(startDate, endDate);
            }
        }

        public static DataTable GetAllTags()
        {
            using (var db = new MainDB())
            {
                return db.StoredProcedures.GetAllTags();
            }
        }

        public int GetInterviewId(long newsId)
        {
            DataTable dt;
            using (var db = new MainDB())
            {
                dt = db.StoredProcedures.GetInterviewId(newsId);
            }
            if (dt != null && dt.Rows.Count == 1)
                return PresentationUtils.Object2Integer(dt.Rows[0][0].ToString());
            return default(int);
        }

        public List<NewsObject> ImportNewsWhileNotEnough(int zoneId, int topHighlight, int topOther)
        {
            if (zoneId > 0)
            {
                var listNews = new List<NewsObject>();
                var top = topHighlight * (topOther + 1);
                var dt = zoneId == DefinedConstants.Zone.TheThao
                             ? GetSportNewsByPosition(top, DefinedConstants.SportNews.TypeIds.NoiBatTrangChu)
                             : GetNewsByPosition(top, DefinedConstants.News.TypeIDs.NoiBatChuyenMuc, zoneId: zoneId);
                if (dt == null || dt.Rows.Count < top)
                {
                    var dtTemp = zoneId == DefinedConstants.Zone.TheThao
                    ? GetNewsByPosition(dt == null ? top : top - dt.Rows.Count, DefinedConstants.SportNews.TypeIds.TinHot)
                    : GetNewsByPosition(dt == null ? top : top - dt.Rows.Count, DefinedConstants.News.TypeIDs.TinTrangChuyenMuc, zoneId: zoneId);
                    if (dt == null)
                    {
                        dt = dtTemp;
                    }
                    else
                        foreach (DataRow r in dtTemp.Rows)
                        {
                            dt.ImportRow(r);
                        }
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    var query = (from DataRow r in dt.Rows
                                 select new NewsObject
                                 {
                                     Title = r[SqlConstants.NewsPublish.Title].ToString(),
                                     Avatar = r[SqlConstants.NewsPublish.Avatar].ToString(),
                                     Url = r[SqlConstants.NewsPublish.Url].ToString()
                                 }).ToList();
                    var topNews = query.Take(topHighlight);

                    var c = 0;
                    foreach (var newsObject in topNews)
                    {
                        newsObject.RelateNews = query.Skip(topHighlight + c * topOther).Take(topOther).ToArray();
                        c++;
                        listNews.Add(newsObject);
                    }
                }
                return listNews;
            }
            return null;
        }
    }
}
